package app.utils;

import com.alibaba.fastjson.JSONObject;

import java.util.LinkedHashMap;

/**
 * @author yuaneg 2018/6/19
 */
public class JsonKeyValue extends LinkedHashMap<String, Object> {

    private int defaultKeyIndex = 1;

    private String defaultKey = "message";

    public JsonKeyValue() {
    }

    public JsonKeyValue(Object value) {
        this.add(value);
    }

    public JsonKeyValue(String k, Object v) {
        this.add(k, v);
    }

    public JsonKeyValue add(String k, Object v) {
        super.put(k, v);
        return this;
    }

    public JsonKeyValue add(Object value) {
        String key = getDefaultKey();
        super.put(key, value);
        defaultKeyIndex++;
        return this;
    }

    private String getDefaultKey() {
        String key = defaultKey + defaultKeyIndex;
        if (super.containsKey(key)) {
            defaultKeyIndex++;
            return getDefaultKey();
        }
        return key;
    }

    @Override
    public String toString() {
        return JSONObject.toJSONString(this);
    }
}